package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.system.service.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.business.domain.WxUser;
import com.ruoyi.business.service.IWxUserService;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private ISysRoleService iSysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

    /**
     * 根据openid加载微信小程序用户
     *
     * @param openid 微信openid
     * @return 用户信息
     */
    public UserDetails loadUserByOpenid(String openid) throws UsernameNotFoundException
    {
        if (StringUtils.isEmpty(openid))
        {
            log.error("微信openid为空");
            throw new ServiceException("微信openid不能为空");
        }

        WxUser wxUser = wxUserService.selectWxUserByOpenid(openid);
        if (StringUtils.isNull(wxUser))
        {
            log.info("微信用户：openid={} 不存在.", openid);
            throw new ServiceException("微信用户不存在");
        }
        else if (wxUser.getStatus() != null && "1".equals(wxUser.getStatus()))
        {
            log.info("微信用户：openid={} 已被停用.", openid);
            throw new ServiceException("微信用户已被停用");
        }

        return createLoginUser(wxUser);
    }

    /**
     * 创建微信用户的登录用户
     *
     * @param wxUser 微信用户
     * @return 登录用户
     */
    public UserDetails createLoginUser(WxUser wxUser) {
        // 创建权限集合
        HashSet<String> permissions = new HashSet<>();
        // 默认角色 USER 可以访问自己的数据
        permissions.add("*:*:*");

        // 创建 LoginUser 对象
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(wxUser.getUserId());

        // 创建系统用户，并分配角色（例如：USER 角色）
        SysUser sysUser = createSysUser(wxUser);
        SysRole sysRole = new SysRole();
        sysRole.setRoleKey("wx");
        List<SysRole> sysRoles = iSysRoleService.selectRoleList(sysRole);
        sysRoles.forEach(e-> System.out.println(e));
        sysUser.setRoles(sysRoles);

        // 设置登录用户的用户信息和权限
        loginUser.setUser(sysUser);
        loginUser.setPermissions(permissions);

        return loginUser;
    }


    /**
     * 将微信用户转换为系统用户对象
     *
     * @param wxUser 微信用户
     * @return 系统用户
     */
    private SysUser createSysUser(WxUser wxUser)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(wxUser.getUserId());
        sysUser.setUserName(wxUser.getOpenid());
        sysUser.setNickName(wxUser.getNickname());
        sysUser.setAvatar(wxUser.getAvatar());

        // 如果有手机号码，设置到系统用户中
        if (StringUtils.isNotEmpty(wxUser.getPhone()))
        {
            sysUser.setPhonenumber(wxUser.getPhone());
        }

        // 如果性别不为空，转换为系统用户格式（0男，1女，2未知）
        if (wxUser.getGender() != null)
        {
            if ("0".equals(wxUser.getGender()))
            {
                sysUser.setSex("0"); // 男
            }
            else if ("1".equals(wxUser.getGender()))
            {
                sysUser.setSex("1"); // 女
            }
            else
            {
                sysUser.setSex("2"); // 未知
            }
        }

        // 设置状态（0正常，1停用）
        if (wxUser.getStatus() != null)
        {
            sysUser.setStatus(wxUser.getStatus());
        }
        else
        {
            sysUser.setStatus("0"); // 默认正常
        }

        // 设置登录时间和IP
        sysUser.setLoginIp(wxUser.getLastLoginIp());
        sysUser.setLoginDate(wxUser.getLastLoginTime());

        return sysUser;
    }
}